import type { PluginOption, ViteDevServer } from 'vite';

import type { AppBuilderOptions } from '../../typing';

import ElectronRunner from './scripts/electron';

/**
 * @Description:自定义构建插件
 * @Author: lishibin
 * @Date: 12:19 2022/1/9
 * @version : V0.0.1-beta
 */

export default async function viteAppPlugin(
  cfg: AppBuilderOptions,
): Promise<PluginOption | undefined> {
  const options = cfg?.tsup;
  // let isServer = false;
  return {
    name: 'vite-plugin-app-runner', // 插件名称
    configureServer(server: ViteDevServer) {
      if (!server || !server.httpServer) {
        return;
      }
      server.httpServer.on('listening', async () => {
        process.env.APP_MODE = server.config.mode || 'development';
        process.env.APP_PORT = `${server.config.server.port}`;
        const targetPlatform = process.env.APP_TARGET || cfg?.target;
        if (targetPlatform === 'electron') {
          const runner = new ElectronRunner(cfg);
          await runner.run(options, server);
        }
      });
    },
    async closeBundle() {
      // if (isServer) {
      //   return;
      // }
      const targetPlatform = process.env.APP_TARGET || cfg?.target;
      if (targetPlatform === 'electron') {
        const runner = new ElectronRunner(cfg);
        await runner.build();
      }
    },
  };
}
